﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.Text;


public partial class aacp : System.Web.UI.Page
{
    public string HTMLOUT;
    public Tournament Tour;
    public string QualifyPlayers;
    public int Pk_Tournament;
    public int TotalPlayers;
    public int TotalMachines;
    public string TournamentName= string.Empty;

    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            AjaxPro.Utility.RegisterTypeForAjax(typeof(aacp));
            Pk_Tournament = int.Parse(Request.QueryString["id"]);
            TotalPlayers = Player.GetPlayersByTournament(Pk_Tournament).Count;
            Session["Pk_Tournament_playoffGeneration"] = Pk_Tournament;
            Tour = new Tournament(Pk_Tournament);
            QualifyPlayers = Tour.QualifyPlayersToPlayOffs.ToString();
            TotalMachines = Machine.GetMachinesByTournament(Pk_Tournament).Count; 
            Configuration rootWebConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
            LoadData(Pk_Tournament);

        }
        catch (Exception Ex) {
            Response.Write(Ex.ToString());
        } 
     
    }
    public void LoadData(int Pk_Tournament) { 
            Tournament oTournament = new Tournament(Pk_Tournament);
            int Rondas = oTournament.QualifyRounds; 
            QualifyRounds oQualifyRounds = new QualifyRounds(Pk_Tournament);
            //oQualifyRounds.Rounds.Sort(new ObjectComparer<QualifyRound>("PlayerNumber ASC, Round_Number ASC", true));
            int[] Scores = (int[])Session["QualifyScores"];
            List<QualifyRound> RoundsWithScore = oQualifyRounds.GetQualifyRoundByPlayerWithScore();
            //Calculamos los puntos
           


            RoundsWithScore.Sort(new ObjectComparer<QualifyRound>("Machine_Number ASC, Score DESC", true));
            List<Player> oPlayers = new List<Player>(); //Donde almacenamos el total;
            int totalPlayers = Player.GetPlayersByTournament(Pk_Tournament).Count;
           
           //Si hay puntuaciones
                int CalculatingMachineFlag;//controla el cambio de máquina
                int CurrentMachineFlag;//controla el cambio de máquina
                int ScoreCounter = 0; // puntero a la puntuación
                CalculatingMachineFlag = RoundsWithScore[0].Machine_Number;
               //TODO COntrolar punuaciones iguales
                //Calculamos los puntos por maquina y hacemos sumatorio
                for (int x = 0; x < RoundsWithScore.Count; x++)
                {
                    CurrentMachineFlag = RoundsWithScore[x].Machine_Number;
                    if (CurrentMachineFlag == CalculatingMachineFlag){
                        RoundsWithScore[x].PositionInRound = ScoreCounter + 1;
                        
                        if (ScoreCounter < Scores.Length)
                        {  //si le toca puntuación
                            RoundsWithScore[x].PointsInRound = Scores[ScoreCounter];
                            if (x > 0 && RoundsWithScore[x - 1].Score != RoundsWithScore[x].Score)
                            {//Verificamos si no es igual a la posicion anterior
                                ScoreCounter++;
                            }
                            else if (x == 0)
                            {
                                ScoreCounter++;
                            }
                        }
                        else
                        {
                            RoundsWithScore[x].PointsInRound = 0;
                        }
                        
                    }
                    else { //Cambiamos de máquina
                        ScoreCounter = 0;
                        RoundsWithScore[x].PointsInRound = Scores[ScoreCounter];
                        RoundsWithScore[x].PositionInRound = ScoreCounter + 1;
                        ScoreCounter++;
                        CalculatingMachineFlag = RoundsWithScore[x].Machine_Number;
                     
                    }
                }


                int CalculatingPlayerFlag;//controla el cambio de máquina
                int CurrentPlayerFlag;//controla el cambio de máquina
                RoundsWithScore.Sort(new ObjectComparer<QualifyRound>("PlayerNumber ASC", true));
               
                CalculatingPlayerFlag = RoundsWithScore[0].PlayerNumber;
                Player oPlayer = new Player(RoundsWithScore[0].PlayerNumber, 0);
                oPlayers.Add(oPlayer);
                //Calculamos los puntos por maquina y hacemos sumatorio
                for (int x = 0; x < RoundsWithScore.Count; x++)
                {
                    CurrentPlayerFlag = RoundsWithScore[x].PlayerNumber;
                    if (CurrentPlayerFlag == CalculatingPlayerFlag)
                    {                       
                        oPlayers[oPlayers.Count - 1].PlayerScore += RoundsWithScore[x].PointsInRound;
                    }
                    else
                    { //Cambiamos de máquina

                        CalculatingPlayerFlag = RoundsWithScore[x].PlayerNumber;
                        oPlayer = new Player(RoundsWithScore[x].PlayerNumber, 0);
                        oPlayers.Add(oPlayer);
                        oPlayers[oPlayers.Count - 1].PlayerScore += RoundsWithScore[x].PointsInRound;
                    }
                }
                
            //}
            RoundsWithScore.Sort(new ObjectComparer<QualifyRound>("PlayerNumber ASC, Round_Number ASC", true));
            oPlayers.Sort(new ObjectComparer<Player>("PlayerScore DESC", true));

            Session["RoundsWithScore_playoffGeneration"] = RoundsWithScore;
            Session["oPlayers_playoffGeneration"] = oPlayers;
            Session["Rondas_playoffGeneration"] = Rondas;
            Session["QualifyPlayersToPlayOffs_playoffGeneration"] = oTournament.QualifyPlayersToPlayOffs;
           
            
            //HTMLOUT = drawTable(RoundsWithScore, oPlayers, Rondas, oTournament.QualifyPlayersToPlayOffs );
            
 
    }
    public string drawTable(List<QualifyRound> oQualifyRounds, List<Player> o_Players, int p_RoundNumber, int p_QualifyPositions)
    {
        try
        {
            if (oQualifyRounds.Count > 0)
            {

                StringBuilder OutPutHTML = new StringBuilder();
                OutPutHTML.Append("<table class=\"Lotery\" style=\"width:780px;text-align:left;border:1px solid black;border-collapse: collapse; padding:5px\">");
                OutPutHTML.Append("<tr style=\"background-color:#ffffff;border:1px solid black; font-weight:bold\">");
                //Header
                OutPutHTML.Append("<td></td>");
                OutPutHTML.Append("<td></td>");
                OutPutHTML.Append("<td>Player</td>");

                for (int x = 0; x < p_RoundNumber; x++)
                {
                    OutPutHTML.AppendFormat("<td>Round {0}</td>", x + 1);
                }
                OutPutHTML.Append("<td style=\"text-align:center\">Points</td>");

                int RowColor = 0;

                int Position = 1;
                Int64 CurrentScore = o_Players[0].PlayerScore;
                for (int x = 0; x < o_Players.Count; x++)
                {
              

                        if (RowColor % 2 == 0)
                        {
                            OutPutHTML.Append("<tr style=\"background-color:#e6e4e4\">");
                        }
                        else
                        {
                            OutPutHTML.Append("<tr style=\"background-color:#ffffff\">");
                        }


                        //Pintamos el jugador
                        //Recorremos las rondas de ese jugador


                        List<QualifyRound> oQualifyRoundsPerPlayer = oQualifyRounds.FindAll(delegate(QualifyRound p) { return p.PlayerNumber == o_Players[x].Player_Number; });
                  
                        //Calculamos su posición
                        if (CurrentScore != o_Players[x].PlayerScore)
                        {
                            Position++;
                        }

                        CurrentScore = o_Players[x].PlayerScore;

                        OutPutHTML.Append("<td style=\"text-align:center\"><input type=\"hidden\" id=\"dato" + x + "\" value=\"" + o_Players[x].Player_Number + "\"><input type=\"checkbox\" id=\"pasa" + x + "\" checked value=\"" + o_Players[x].Pk_Player + "\"><input onblur=\"actualiza(this)\" style=\"width:30px\" type=\"input\" id=\"posicion" + x + "\" value=\"" + Position + "\"></td>");
                     
                       
                        OutPutHTML.AppendFormat("<td style=\"text-align:center\">{0}º</td>", Position);
                        OutPutHTML.AppendFormat("<td><b><img style=\"vertical-align:middle;\" src=\"img/player_flags/b{0}.png\"/> {1}</b> (#{2})</td>", oQualifyRoundsPerPlayer[0].Pk_Player_Zone, oQualifyRoundsPerPlayer[0].Player_Nick, oQualifyRoundsPerPlayer[0].PlayerNumber);

                        List<QualifyRound> oQualifyRoundsFree;
                        oQualifyRoundsFree = oQualifyRoundsPerPlayer.FindAll(delegate(QualifyRound p) { return p.Round_Number == -1; });
                                  

                        for (int y = 0; y < p_RoundNumber; y++)
                        {
                             QualifyRound oQualifyRoundsT;
                                
                                //Check if is round free tournament
                                oQualifyRoundsT = oQualifyRoundsPerPlayer.Find(delegate(QualifyRound p) { return p.Round_Number == y + 1; });

                                if (oQualifyRoundsFree != null)
                                {
                                    if (y < oQualifyRoundsFree.Count)
                                    {
                                        
                                            OutPutHTML.AppendFormat("<td>{0} ({1}º) <img style=\"vertical-align:middle;width:15px\" src=\"img/joker.gif\"/></td>", oQualifyRoundsFree[y].Machine_Acron, oQualifyRoundsFree[y].PositionInRound);
                                         
                                    }
                                    else
                                    {
                                        OutPutHTML.AppendFormat("<td></td>");
                                    }

                                }
                                else
                                {

                                    if (oQualifyRoundsT != null)
                                    {
                                        if (oQualifyRoundsT.IsJoker == true)
                                        {
                                            OutPutHTML.AppendFormat("<td>{0} ({1}º) <img style=\"vertical-align:middle;width:15px\" src=\"img/joker.gif\"/></td>", oQualifyRoundsT.Machine_Acron, oQualifyRoundsT.PositionInRound);
                                        }
                                        else
                                        {
                                            OutPutHTML.AppendFormat("<td>{0} ({1}º)</td>", oQualifyRoundsT.Machine_Acron, oQualifyRoundsT.PositionInRound);
                                        }
                                    }
                                    else
                                    {
                                        OutPutHTML.AppendFormat("<td></td>");
                                    }
                                }
                        }
                        OutPutHTML.AppendFormat("<td style=\"text-align:center\">{0}</td>", o_Players[x].PlayerScore);
                        OutPutHTML.Append("</tr>");
                        RowColor++;
                }

                OutPutHTML.Append("</table>");
                return OutPutHTML.ToString();
            }
            else
            {
                return string.Empty;
            }

        }
        catch (Exception Ex) {
            return Ex.ToString();
        } 
    }

    

    [AjaxPro.AjaxMethod(AjaxPro.HttpSessionStateRequirement.Read)]
    public string GetTable()
    {
        try
        {


            string res = drawTable((List<QualifyRound>)Session["RoundsWithScore_playoffGeneration"], (List<Player>)Session["oPlayers_playoffGeneration"], (int)Session["Rondas_playoffGeneration"], (int)Session["QualifyPlayersToPlayOffs_playoffGeneration"]);
           
            return res;
        }
        catch(Exception)
        {
            return string.Empty;
        }
    }
   

    [AjaxPro.AjaxMethod(AjaxPro.HttpSessionStateRequirement.Read)]
    public Boolean SavePositions(string p_list)
    {
        try {
            string[] Lista = p_list.Split('|');
            Tournament oTournament = new Tournament((int)Session["Pk_Tournament_playoffGeneration"]);
            foreach (string Item in Lista)
            {
                string[] Datos = Item.Split('#');

                int player_number = int.Parse(Datos[0]);
                int posicion = int.Parse(Datos[1]);

                QualifyRounds.SetPlayerAACPPosition(posicion, oTournament.Pk_Tournament, player_number);
            }

            return true;
        } 
        catch (Exception)
        {
            return false;
        }
    }

    [AjaxPro.AjaxMethod(AjaxPro.HttpSessionStateRequirement.Read)]
    public Boolean SavePlayOffs(string p_list,string p_machines)
    {
        try
        {
            string[] Lista = p_list.Split('|');
            string[] ListaMachines = p_machines.Split('|');

            //List<QualifyRound> oQualifyRound = (List<QualifyRound>)Session["RoundsWithScore"];
            PlayoffRounds lPlayoffRound = new PlayoffRounds();
            Tournament oTournament = new Tournament((int)Session["Pk_Tournament_playoffGeneration"]);
            //List<Machine> oMachines = Machine.GetMachinesByTournament(oTournament.Pk_Tournament);
            List<Player> oPlayers = new List<Player>();
 
            foreach (string Item in Lista) {                
                Player oPlayer = Player.GetPlayerByNumber(int.Parse(Item)); 
                oPlayers.Add(oPlayer); 
                                                              
            }

            List<Machine> oMachines = new List<Machine>();
            foreach (string Item in ListaMachines)
            {
                Machine oMachine = Machine.GetMachineByMachineNumber(int.Parse(Item), (int)Session["Pk_Tournament_playoffGeneration"]);
                oMachines.Add(oMachine);

            }

           
            

            Lotery.MakePlayOffs(oMachines, oPlayers, oTournament,ref lPlayoffRound);
            PlayoffRounds.SavePlayOff(lPlayoffRound.Rounds);

            return true;
           
               
        }
        catch (Exception)
        {
            return false;
        }
    }
}

